package com.iot08.api.queue;

import com.alibaba.fastjson.JSONObject;
import com.iot08.api.service.supplement.TCPService;
import com.iot08.api.utils.StringTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author cwj
 * @description
 * @date 2025/6/4 14:13
 **/
@Component
@Slf4j
public class TaskConsumerScheduler {
    @Resource
    private TCPService tcpService;

    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    //private final ExecutorService workerPool = Executors.newFixedThreadPool(2); // 并发处理线程数


    @PostConstruct
    public void start() {
        scheduler.scheduleAtFixedRate(() -> {
        //scheduler.scheduleWithFixedDelay(() -> {
            try {
                JSONObject task = LimitedSingleQueue.getInstance().poll();
                //log.info("定时任务信息：{}",task);
                if (task != null) {
                /*workerPool.submit(() -> {
                    log.info("队列消费了定位数据......");
                    String imei = task.getString("imei");
                    Integer userWeiZhiLocatteBL = task.getInteger("useWeiZhiLocateBL");
                    log.info("处理任务: " + StringTool.subStringByLength(task.toJSONString(),100) + " by " + Thread.currentThread().getName());
                    //解析数据
                    tcpService.useWeiZhiLocateBL = Double.valueOf(userWeiZhiLocatteBL);
                    tcpService.cmdTempFunc(imei, task);
                });*/
                //long startTime = System.currentTimeMillis();
                //log.info("队列消费了定位数据，开始调度时间：{}",startTime);
                //log.info("队列消费了定位数据......");
                String imei = task.getString("imei");
                Integer userWeiZhiLocatteBL = task.getInteger("useWeiZhiLocateBL");
                log.info("处理任务: " + StringTool.subStringByLength(task.toJSONString(),100) + " by " + Thread.currentThread().getName());
                //解析数据
                tcpService.useWeiZhiLocateBL = Double.valueOf(userWeiZhiLocatteBL);
                tcpService.cmdTempFunc(imei, task);
                //long endTime = System.currentTimeMillis();
                //log.info("结束调度时间：{},调度任务所有时间为：{}",endTime,endTime-startTime);
               }
            } catch (Exception e) {
                log.error("队列消费任务时发生异常", e);
            }
        }, 0, 35, TimeUnit.MILLISECONDS);
    }

    @PreDestroy
    public void shutdown() {
        log.info("正在关闭线程池......");
        scheduler.shutdown();
        //workerPool.shutdown();
        try {
            if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {
                scheduler.shutdownNow();
            }
            /*if (!workerPool.awaitTermination(10, TimeUnit.SECONDS)) {
                workerPool.shutdownNow();
            }*/
        } catch (InterruptedException e) {
            scheduler.shutdownNow();
            //workerPool.shutdownNow();
            Thread.currentThread().interrupt();
        }
        log.info("线程池已关闭......");
    }

   /* @Scheduled(fixedDelay = 35)
    public void consumeTask() {
        JSONObject task = LimitedSingleQueue.getInstance().poll();
        if (task != null) {
            try {
                log.info("消费定位数据...");
                String imei = task.getString("imei");
                Integer userWeiZhiLocatteBL = task.getInteger("useWeiZhiLocateBL");
                 log.info("处理任务: " + StringTool.subStringByLength(task.toJSONString(),100) + " by " + Thread.currentThread().getName());
                // 处理逻辑（不使用共享字段）
                tcpService.useWeiZhiLocateBL = Double.valueOf(userWeiZhiLocatteBL);
                tcpService.cmdTempFunc(imei, task);
            } catch (Exception e) {
                log.error("消费任务异常: {}", task, e);
            }
        }
    }*/
}
